package com.zhkj.crawl.config.okhttp;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * for okhttp
 */
public class CustomCookieJar implements CookieJar {
    Map<String, Cookie> cache = new HashMap<>();

    @Override
    public void saveFromResponse(HttpUrl httpUrl, List<Cookie> cookies) {
        for (Cookie cookie : cookies) {
            cache.put(cookie.name(), cookie);
        }
    }

    //Http发送请求前回调，Request中设置Cookie
    @Override
    public List<Cookie> loadForRequest(HttpUrl url) {
        //有效的Cookie
        List<Cookie> validCookies = new ArrayList<>();

        for (Cookie cookie : cache.values()) {
            if (cookie.expiresAt() < System.currentTimeMillis()) {
                cache.remove(cookie.name());
            } else if (cookie.matches(url)) {
                validCookies.add(cookie);
            }
        }


        return validCookies;
    }
}
